<?php
/**
 * Created by PhpStorm.
 * User: simon
 * Date: 2016/11/20
 * Time: 8:48
 */

namespace App\Weixin;


use App\Common\WeixinTokenCacher;
use App\Kids\Caches\AuthApps;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;

class WechatClientFactory
{

    static public function newClient($companyIdorAppId = 0)
    {
        Log::debug("创建微信接入客户端,传入参数 $companyIdorAppId ");
        if (empty($companyIdorAppId) || $companyIdorAppId === 0) {
            return self::newComponetClient();
        }
        $isAppId = !is_int($companyIdorAppId) && strlen($companyIdorAppId) > 10;
        $appId = null;
        if ($isAppId) {
            $appId = $companyIdorAppId;
        } else {
            $appId = AuthApps::findAppId($companyIdorAppId);
        }

        Log::debug("创建微信接入客户端,appId is $appId");
        $client = self::newClientFromConfig($appId);
        if ($client !== false) {
            return $client;
        }
        Log::debug("微信配置文件中找不到 $appId 的配置信息");

        $client = self::newClientFromCache($appId);
        if ($client !== false) {
            Log::debug("通过缓存中的授权信息为 $appId 创建接入微信客户端");
            return $client;
        }
        Log::error("通过缓存中的授权信息为 $appId 创建接入微信客户端失败");
        return false;
    }

    public static function newComponetClient()
    {
        $options = self::getComponentConfigs();
        $client = new WechatServiceClient($options);
        $client->configComponents($options);
        return $client;
    }

    public static function newClientFromConfig($appid)
    {
        $configs = Config::get("weixin.apps");
        if (array_key_exists($appid, $configs)) {
            $client = new WechatServiceClient($configs[$appid]);
            $client->configComponents(self::getComponentConfigs());
            return $client;
        }
        return false;
    }

    /**
     * 通过缓存中的授权信息创建接入微信客户端
     * @param $appid
     * @return WechatServiceClient|bool
     */
    public static function newClientFromCache($appid)
    {
        $client = new WechatServiceClient();
        $componentConfigs = self::getComponentConfigs();
        $client->configComponents($componentConfigs);
        $infoBean = WeixinTokenCacher::getAuthrizeInfoBean($appid);
        if (empty($infoBean) || $infoBean === false) {
            Log::error("授权应用 $appid 的接入码缓存找不到");
            return false;
        }
        $authorizedAccessToken = $infoBean->get_parameter_value();
        $options = ["appid" => $appid, "appsecret" => $componentConfigs["component_appsecret"]];// TODO 不知道是否正确
        $wechat = new Wechat($options);
        $wechat->cacheAccessToken($appid, $authorizedAccessToken);
        Log::debug("采用授权的方式返回wechat， appid=$appid , auth tokent= $authorizedAccessToken");
        Log::debug("采用应用组件的 appsecret ： " . $componentConfigs["component_appsecret"]);
        return $wechat;
    }

    public static function getComponentConfigs()
    {
        $verifyTicket = WeixinTokenCacher::getComponentVerifyTicket();
        return [
            "token" => "0tong100",
            "appid" => "wx979a197c073bf48a",
            "appsecret" => "73ab1ff9469a7d1bacae9f0903d986b5",
            "encodingaeskey" => "hutkheSIflAt1AGsE0vFXNZKX69hFzYQkDmJXfDSxw2",
            "component_token" => "0tong100",
            "component_appid" => "wx979a197c073bf48a",
            "component_appsecret" => "73ab1ff9469a7d1bacae9f0903d986b5",
            "component_encodingaeskey" => "hutkheSIflAt1AGsE0vFXNZKX69hFzYQkDmJXfDSxw2",
            "component_verify_ticket" => $verifyTicket,
        ];
    }


}